import { defineStore } from 'pinia'
import { ref } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'

export const useSingleSelectStore = defineStore('singleSelect', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const title = ref('')
  const options = ref([])
  const selectedIndex = ref(-1)
  const defaultIndex = ref(-1)
  const isConfirmed = ref(false)

  // 动作
  function initialize(dialogTitle, dialogOptions, defaultIdx) {
    title.value = dialogTitle
    options.value = dialogOptions
    selectedIndex.value = defaultIdx
    defaultIndex.value = defaultIdx
    isConfirmed.value = false
  }

  function selectOption(index) {
    selectedIndex.value = index
  }

  function confirm() {
    isConfirmed.value = true
    hide()
  }

  function show(dialogTitle, dialogOptions, defaultIdx = -1) {
    return dialogQueue.show({
      onLoaded: () => initialize(dialogTitle, dialogOptions, defaultIdx),
      onHidden: () => isConfirmed.value ? selectedIndex.value : defaultIndex.value
    })
  }

  function hide() {
    dialogQueue.hide(isConfirmed.value ? selectedIndex.value : defaultIndex.value)
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    title,
    options,
    selectedIndex,
    // 动作
    selectOption,
    confirm,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
})